package com.flanz.apache.velocity.uimocker;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;

public class MacrosCollector {
	final public String REPRO_MACRO_FILENAME = "VM_global_library.vm";
	private String macros = "";

	public MacrosCollector(DiscResourceCollector collector, String projectMacrosFileList) {
		if (StringUtils.isNotBlank(projectMacrosFileList)) {
			String fileContent = collector.readFile(projectMacrosFileList);
			macros = readMacroContent(collector, fileContent);
		}
	}

	private String readMacroContent(DiscResourceCollector collector, String fileContent) {
		boolean fileIncludeListMode = fileContent.startsWith("/");
		StringBuilder sb = new StringBuilder();
		if (fileIncludeListMode) {
			// include files
			StringTokenizer token = new StringTokenizer(fileContent);
			Map<String, String> resolveAll_VM = collector.resolveAll();

			while (token.hasMoreTokens()) {
				String nextToken = token.nextToken();
				System.out.println("LOAD_MACROFILE:" + nextToken);
				String content = resolveAll_VM.get(nextToken);
				sb.append(content);
			}
		} else {
			sb.append(fileContent);
		}
		return sb.toString();
	}

	public String getMacros() {
		return this.macros;
	}

	public void putMacrosToRepro(DiscResourceCollector collector) {
		if (StringUtils.isNotBlank(macros)) {
			Map<String, String> virtualFiles = new HashMap<String, String>();
			virtualFiles.put(REPRO_MACRO_FILENAME, getMacros());
			collector.setVirtualResource(virtualFiles);
		}

	}
}
